package com.sca.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sca.auth.constant.RedisKeyConstant;
import com.sca.auth.dto.response.LoginResponse;
import com.sca.auth.entity.User;
import com.sca.auth.repository.UserMapper;
import com.sca.auth.service.UserService;
import com.sca.auth.utils.JwtUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author liuxianfei
 * @since 2020/10/30 10:52
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final RedisTemplate<String, Object> redisTemplate;

    public UserServiceImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePassword(Integer userId, String password) {
        User user = this.getById(userId);
        if (user != null && !StringUtils.isEmpty(password)) {
            User updateUser = new User();
            updateUser.setId(userId);
            updateUser.setVersion(user.getVersion());
            updateUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
            return this.updateById(updateUser);
        }
        return false;
    }

    @Override
    public LoginResponse login(String username, String password) {
        User one = this.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username).eq(User::getPassword, DigestUtils.md5DigestAsHex(password.getBytes())));
        if (one != null) {
            LoginResponse response = new LoginResponse();
            response.setUsername(one.getUsername());
            String token = JwtUtil.generateToken(one.getId());
            response.setToken(token);
            redisTemplate.opsForValue().set(RedisKeyConstant.AUTH_STR_USER_TOKEN + one.getId(), token, 7200, TimeUnit.SECONDS);
            return response;
        }
        return null;
    }

}
